package com.lv.service.dialog

import android.content.Context
import android.graphics.Color
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.github.gzuliyujiang.wheelpicker.widget.LinkageWheelLayout
import com.lv.common.imp.OnPositionTMore
import com.lv.common.utils.YgxUtilsKt
import com.lv.service.R
import com.lv.service.room.category.CategoryBean
import com.lv.service.utils.YgxToolsKt
import com.lv.service.weidget.picker.ThirdLikeProvider
import com.lxj.xpopup.core.BottomPopupView

/**
 * 作者： ygx
 * 创建日期：2022/10/10 10:32 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class TimeStartEndPopupView(
    private val mContext: Context,
    private val mTitle: String = "",
    private var mStartTime: String = "",
    private var mEndTime: String = "",
    private val bg: Int = com.lv.common.R.drawable.bg_theme_25,
    private val startData: String = "",//日历开始时间
    private val endData: String = "",//日历结束时间
    private val showUnit: Boolean = false,
    private val positionListener: OnPositionTMore<String>? = null
) :
    BottomPopupView(mContext), OnClickListener {

    private var mWheelStartPosition1: Int = 0
    private var mWheelStartPosition2: Int = 0
    private var mWheelStartPosition3: Int = 0
    private var mWheelEndPosition1: Int = 0
    private var mWheelEndPosition2: Int = 0
    private var mWheelEndPosition3: Int = 0
    private val mTimeCusBeans = mutableListOf<CategoryBean>()

    private var tvTitleCustom: TextView? = null
    private var tvStart: TextView? = null
    private var tvEnd: TextView? = null
    private var tvSure: TextView? = null
    private var wheelLinkageCus: LinkageWheelLayout? = null
    private var clContainerTop: ConstraintLayout? = null
    private var ivClose: ImageView? = null
    private var viewStartLine: View? = null
    private var viewEndLine: View? = null
    private var viewTop: View? = null
    private var timeCurrent: Int = 0
//    private val mMonday = TimeUtil.getDayOfWeek(1, "yyyy-MM-dd")//本周一的日期
//    private val mTodayday = TimeUtil.getNowDateTime("yyyy-MM-dd")//今天的日期
//    private var mProMonday = ""//上周一的日期
//    private var mProSunday = ""//上周日的日期
//    private var mPro2Monday = ""//上上周一的日期
//    private var mPro2Sunday = ""//上上周日的日期
//    private var mMonth = String.format("%02d", TimeUtil.getMonth()) //当前月

    private val mViewList = mutableListOf<View>()

    override fun getImplLayoutId(): Int {
        return R.layout.time_start_end_popup
    }

    override fun onCreate() {
        super.onCreate()
        //上上周
//        mPro2Monday = TimeUtil.getPreviousDaysDate(14, mMonday, "yyyy-MM-dd")
//        mPro2Sunday = TimeUtil.getBeforDaysDate(6, mPro2Monday, "yyyy-MM-dd")

        //上周
//        mProMonday = TimeUtil.getPreviousDaysDate(7, mMonday, "yyyy-MM-dd")
//        mProSunday = TimeUtil.getBeforDaysDate(6, mProMonday, "yyyy-MM-dd")
        if (startData != "" && endData != "") {
            val times = YgxToolsKt.initSelectedStaEndTime(startData, endData, showUnit)
            mTimeCusBeans.addAll(times)
        } else {
            val times = YgxToolsKt.initSelectedNoAllTime(2029, 12, 31, showUnit = showUnit)
            mTimeCusBeans.addAll(times)
        }
        if (mStartTime.isNotEmpty() && mStartTime.contains("-")) {
            val startSplit = mStartTime.split("-")
            val (a, b, c) = YgxToolsKt.initThirdAddressInt(
                mTimeCusBeans, startSplit[0], startSplit[1], startSplit[2]
            )
            mWheelStartPosition1 = a
            mWheelStartPosition2 = b
            mWheelStartPosition3 = c
        }
        if (mEndTime.isNotEmpty() && mEndTime.contains("-")) {
            val endSplit = mEndTime.split("-")
            val (d, e, f) = YgxToolsKt.initThirdAddressInt(
                mTimeCusBeans, endSplit[0], endSplit[1], endSplit[2]
            )
            mWheelEndPosition1 = d
            mWheelEndPosition2 = e
            mWheelEndPosition3 = f
        }
        viewTop = findViewById<View>(R.id.view_top)
        tvTitleCustom = findViewById<TextView>(R.id.tv_title)
        tvStart = findViewById<TextView>(R.id.tv_start)
        tvEnd = findViewById<TextView>(R.id.tv_end)
        tvSure = findViewById<TextView>(R.id.tv_sure)
        wheelLinkageCus = findViewById<LinkageWheelLayout>(R.id.wheel_linkage_cus)
        clContainerTop = findViewById<ConstraintLayout>(R.id.cl_container_top)
        ivClose = findViewById<ImageView>(R.id.iv_close)
        viewStartLine = findViewById<View>(R.id.view_start_line)
        viewEndLine = findViewById<View>(R.id.view_end_line)
        viewTop?.setOnClickListener(this)
        tvTitleCustom?.setOnClickListener(this)
        tvSure?.setOnClickListener(this)
        ivClose?.setOnClickListener(this)
        tvStart?.setOnClickListener(this)
        tvEnd?.setOnClickListener(this)
        tvSure?.setBackgroundResource(bg)
        initView()
        initEvnet()
        initCustomTime()
        tvTitleCustom?.text = mTitle
    }

    private fun initView() {

        val thirdLikeCusProvider = ThirdLikeProvider(mTimeCusBeans)
        wheelLinkageCus?.setData(thirdLikeCusProvider)

        wheelLinkageCus?.setDefaultValue(
            mWheelStartPosition1,
            mWheelStartPosition2,
            mWheelStartPosition3
        )
        wheelLinkageCus?.firstWheelView?.visibility = View.VISIBLE
        wheelLinkageCus?.secondWheelView?.visibility = View.VISIBLE
        wheelLinkageCus?.thirdWheelView?.visibility = View.VISIBLE
    }


    private fun initCustomTime() {
        when (timeCurrent) {
            0 -> {
                if (mStartTime.isEmpty()) {
                    mWheelStartPosition1 = (mTimeCusBeans.size) - 1
                    mWheelStartPosition2 =
                        (mTimeCusBeans[mWheelStartPosition1].telSecondCategories?.size ?: 0) - 1
                    mWheelStartPosition3 =
                        (mTimeCusBeans[mWheelStartPosition1].telSecondCategories?.get(
                            mWheelStartPosition2
                        )?.telThirdCategories?.size ?: 0) - 1
                    mStartTime = "${mTimeCusBeans[mWheelStartPosition1].name}-${
                        mTimeCusBeans[mWheelStartPosition1].telSecondCategories?.get(
                            mWheelStartPosition2
                        )?.name
                    }-${
                        mTimeCusBeans[mWheelStartPosition1].telSecondCategories?.get(
                            mWheelStartPosition2
                        )?.telThirdCategories?.get(mWheelStartPosition3)?.name
                    }"
                } else {
                    initStartScanTimePicker()
                }
                wheelLinkageCus?.setDefaultValue(
                    mWheelStartPosition1,
                    mWheelStartPosition2,
                    mWheelStartPosition3
                )
                tvStart?.text = mStartTime
                tvEnd?.text = mEndTime
                tvStart?.setTextColor(Color.parseColor("#eb613d"))
                viewStartLine?.setBackgroundResource(com.lv.common.R.drawable.bg_theme_2)
                tvEnd?.setTextColor(Color.parseColor("#242424"))
                viewEndLine?.setBackgroundResource(com.lv.common.R.drawable.bg_24_2)
            }

            1 -> {
                if (mEndTime.isEmpty()) {
                    mWheelEndPosition1 = (mTimeCusBeans?.size ?: 0) - 1
                    mWheelEndPosition2 =
                        (mTimeCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.size ?: 0) - 1
                    mWheelEndPosition3 =
                        (mTimeCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.get(
                            mWheelEndPosition2
                        )?.telThirdCategories?.size ?: 0) - 1
                    mEndTime = "${mTimeCusBeans?.get(mWheelEndPosition1)?.name}-${
                        mTimeCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.get(
                            mWheelEndPosition2
                        )?.name
                    }-${
                        mTimeCusBeans?.get(mWheelEndPosition1)?.telSecondCategories?.get(
                            mWheelEndPosition2
                        )?.telThirdCategories?.get(mWheelEndPosition3)?.name
                    }"
                } else {
                    initEndScanTimePicker()
                }
                wheelLinkageCus?.setDefaultValue(
                    mWheelEndPosition1,
                    mWheelEndPosition2,
                    mWheelEndPosition3
                )
                tvStart?.text = mStartTime
                tvEnd?.text = mEndTime
                tvStart?.setTextColor(Color.parseColor("#242424"))
                viewStartLine?.setBackgroundResource(com.lv.common.R.drawable.bg_24_2)
                tvEnd?.setTextColor(Color.parseColor("#eb613d"))
                viewEndLine?.setBackgroundResource(com.lv.common.R.drawable.bg_theme_2)
            }
        }
    }

    private fun initStartScanTimePicker() {
        val list = mutableListOf<CategoryBean>()
        mTimeCusBeans.let { list.addAll(it) }
        val startSplit = mStartTime.split("-")
        val (x, y, z) = YgxToolsKt.initThirdAddressInt(
            list,
            startSplit[0],
            String.format("%02d", startSplit[1].toDouble().toInt()),
            String.format("%02d", startSplit[2].toDouble().toInt())
        )
        mWheelStartPosition1 = x
        mWheelStartPosition2 = y
        mWheelStartPosition3 = z
    }

    private fun initEndScanTimePicker() {
        val list = mutableListOf<CategoryBean>()
        mTimeCusBeans.let { list.addAll(it) }
        val endSplit = mEndTime.split("-")
        val (a, b, c) = YgxToolsKt.initThirdAddressInt(
            list,
            endSplit[0],
            String.format("%02d", endSplit[1].toDouble().toInt()),
            String.format("%02d", endSplit[2].toDouble().toInt())
        )
        mWheelEndPosition1 = a
        mWheelEndPosition2 = b
        mWheelEndPosition3 = c
    }

    private fun initEvnet() {
        wheelLinkageCus?.setOnLinkageSelectedListener { first, second, third ->
            val position1 = wheelLinkageCus?.firstWheelView?.currentPosition ?: 0
            val position2 = wheelLinkageCus?.secondWheelView?.currentPosition ?: 0
            val position3 = wheelLinkageCus?.thirdWheelView?.currentPosition ?: 0
            val time = "${mTimeCusBeans[position1].name}-${
                mTimeCusBeans[position1].telSecondCategories?.get(
                    position2
                )?.name
            }-${
                mTimeCusBeans[position1].telSecondCategories?.get(
                    position2
                )?.telThirdCategories?.get(position3)?.name
            }"
            when (timeCurrent) {
                0 -> {
                    mWheelStartPosition1 = position1
                    mWheelStartPosition2 = position2
                    mWheelStartPosition3 = position3
                    mStartTime = time
                    tvStart?.text = mStartTime
                }

                1 -> {
                    mWheelEndPosition1 = position1
                    mWheelEndPosition2 = position2
                    mWheelEndPosition3 = position3
                    mEndTime = time
                    tvEnd?.text = mEndTime
                }
            }
            initTagView()

//            mBinding.tvSearchCategory.text =
//                "${mAllBeans!![mWheelPosition1].name}-${mAllBeans[mWheelPosition1].telSecondCategories!![mWheelPosition2].name}"
        }

    }

    private fun initTagView() {
        mViewList.forEach { viewItem ->
            viewItem.setBackgroundResource(com.lv.common.R.drawable.bg_f9_15)
        }
//        LogUtils.e("mStartTime==${mStartTime}==mMonday==${mMonday}==mEndTime==${mEndTime}==mTodayday==${mTodayday}")
//        LogUtils.e("mStartTime==${mStartTime}==mProMonday==${mProMonday}==mEndTime==${mEndTime}==mProSunday==${mProSunday}")
//        LogUtils.e("mStartTime==${mStartTime}==mPro2Monday==${mPro2Monday}==mEndTime==${mEndTime}==mPro2Sunday==${mPro2Sunday}")

    }


    override fun onDestroy() {
        super.onDestroy()
    }

    override fun beforeDismiss() {
        super.beforeDismiss()

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.view_top, R.id.iv_close -> {
//                positionListener?.onClick(
//                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, data = null
//                )
                dismiss()
            }

            R.id.tv_start -> {
                if (timeCurrent != 0) {
                    timeCurrent = 0
                    initCustomTime()
                }
            }

            R.id.tv_end -> {
                if (timeCurrent != 1) {
                    timeCurrent = 1
                    initCustomTime()
                }
            }

            R.id.tv_sure -> {
//                    val days = TimeUtil.getDaysBetweenDates(mStartTime, mEndTime, "yyyy-MM-dd")
//                    if (days > 29) {
//                        showToast("请选择30天内数据对比")
//                        return
//                    }
                val result = YgxUtilsKt.compareDates(mStartTime, mEndTime)
                when (result) {
                    0 -> {//两个日期相同
//                        if (mStartTime == mTodayday) {
//                            mWheelPos = 0
//                        } else {
//                            mWheelPos = 3
//                        }
                    }

                    1 -> {//第一个日期晚于第二个日期
                        val tempTime = mStartTime
                        mStartTime = mEndTime
                        mEndTime = tempTime
                        val po1 = mWheelStartPosition1
                        val po2 = mWheelStartPosition2
                        val po3 = mWheelStartPosition3
                        mWheelStartPosition1 = mWheelEndPosition1
                        mWheelStartPosition2 = mWheelEndPosition2
                        mWheelStartPosition3 = mWheelEndPosition3
                        mWheelEndPosition1 = po1
                        mWheelEndPosition2 = po2
                        mWheelEndPosition3 = po3
                        initTagView()
                    }

                    else -> {
                    }
                }


                positionListener?.onClick(
                    0, mStartTime, mEndTime
                )
                dismiss()
            }
        }
    }


}